<script setup lang="ts">
import { ref, onMounted, watch } from "vue";

interface Props {
  modelVlaue?: Array<Date>;
  start?: Date;
  end?: Date;
  width?: number;
}

const props = withDefaults(defineProps<Props>(), {
  modelVlaue: [],
  start: undefined,
  end: undefined,
  width: 330
});
const emit = defineEmits([
  "update:modelValue",
  "change",
  "update:start",
  "update:end"
]);
const shortcuts = [
  {
    text: "最近15分钟",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMinutes(end.getMinutes() - 15);
      return [start, end];
    }
  },
  {
    text: "最近1小时",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMinutes(end.getMinutes() - 60);
      return [start, end];
    }
  },
  {
    text: "最近4小时",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMinutes(end.getMinutes() - 240);
      return [start, end];
    }
  },
  {
    text: "最近12小时",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMinutes(end.getMinutes() - 720);
      return [start, end];
    }
  },
  {
    text: "最近24小时",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMinutes(end.getMinutes() - 1440);
      return [start, end];
    }
  },
  {
    text: "最近7天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMinutes(end.getMinutes() - 10080);
      return [start, end];
    }
  },
  {
    text: "最近30天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMinutes(end.getMinutes() - 43200);
      return [start, end];
    }
  }
];
const time = ref([]);
const onChangeHandle = () => {
  emit("update:modelValue", time.value);
  emit("update:start", time.value?.length ? time.value[0] : undefined);
  emit("update:end", time.value?.length ? time.value[1] : undefined);
  emit("change", {
    time: time.value,
    startTime: time.value[0],
    endTime: time.value[1]
  });
};
onMounted(() => {
  if (props.start && props.end) {
    time.value = [new Date(props.start), new Date(props.end)];
  }
  if (props.modelVlaue) {
    time.value = props.modelVlaue;
  }
});
watch(
  () => props.start,
  newV => {
    if (!newV) {
      time.value = [];
    }
  },
  {
    immediate: true
  }
);
</script>
<template>
  <el-date-picker
    :style="{ width: width +'px'}"
    @change="onChangeHandle"
    v-model="time"
    type="datetimerange"
    :shortcuts="shortcuts"
    range-separator="至"
    start-placeholder="开始时间"
    end-placeholder="结束时间"
  />
</template>
<style scoped></style>
